package com.rhzy.wnhc.handller;

import com.rhzy.wnhc.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;


/**
 * 异常处理器
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class DefineExceptionHandler {


    /**
     * 处理请求参数错误
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleValidationExceptions(HttpServletRequest request, MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        log.error("【请求路径为：{}，错误为：{}】",request.getRequestURI(),ex.getMessage());
        return AjaxResult.addError(errors.toString());
    }

    /**
     * 处理请求参数错误
     * @param ex
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public AjaxResult handleConstraintViolationException(HttpServletRequest request, ConstraintViolationException ex) {
        log.error("【请求路径为：{}，错误为：{}】",request.getRequestURI(),ex.getMessage());
        return AjaxResult.addError(ex.getMessage());
    }

}
